package com.dong.c07_netty_simple;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.util.Random;

/**
 * <h1></h1>
 * Inbound :入栈
 * @author : dzj
 * @create: 2020-03-19 20:59
 */
public class NettyClientHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 通道就绪
        System.out.println("client:"+ctx);
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello, server : (￢_￢),  客户端建立连接", CharsetUtil.UTF_8));
    }
    //当通道有读取事件时, 会触发
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
       // super.channelRead(ctx, msg);
        ByteBuf buf = (ByteBuf) msg;
        System.out.println("服务器回复的消息: "+buf.toString(CharsetUtil.UTF_8));
        System.out.println("服务器的地址:"+ctx.channel().remoteAddress());
        Random random = new Random();
        int i = random.nextInt(100);
        if(i>50) {
            ctx.channel().writeAndFlush(Unpooled.copiedBuffer("很高兴认识你哈 ...", CharsetUtil.UTF_8));
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //
        cause.printStackTrace();
        ctx.close();
    }
}
